package com.woniu.darryringmall.admin.controller;

import com.woniu.darryringmall.admin.entity.Manager;
import com.woniu.darryringmall.admin.jwt.Audience;
import com.woniu.darryringmall.admin.jwt.JwtUtil;
import com.woniu.darryringmall.admin.service.ManagerService;
import com.woniu.darryringmall.utils.ResponseData;
import com.woniu.darryringmall.utils.ResponseUtils;
import com.woniu.darryringmall.utils.ResultStateCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * 管理员controller层
 */
@RestController
@RequestMapping("admin/manager")
public class ManagerController {
    @Autowired
    private ManagerService managerService;
    @Autowired
    private Audience audience;

    @RequestMapping("login")
    public ResponseData login(@RequestBody Manager manager, HttpServletResponse response) {
        UsernamePasswordToken token = new UsernamePasswordToken(manager.getAccount(), manager.getPassword());
        Subject currSubject = SecurityUtils.getSubject();
        try {
            currSubject.login(token);
            Manager loginManager = managerService.getByAccount(manager.getAccount());
            response.addHeader("jwt", JwtUtil.createJWT(loginManager.getId(), loginManager.getAccount(), audience));
            return ResponseUtils.SUCCESS;
        } catch (AuthenticationException ae) {
            if (ae instanceof UnknownAccountException)
                return new ResponseData(ResultStateCode.FAIL, "账号错误");
            else if (ae instanceof IncorrectCredentialsException)
                return new ResponseData(ResultStateCode.FAIL, "密码错误");
        }
        return new ResponseData(ResultStateCode.FAIL, "操作失败");
    }

    @RequestMapping("getManager")
    public ResponseData getManager(@RequestHeader("jwt") String jwt) {
        int id = JwtUtil.getId(jwt, audience.getBase64Secret());
        return ResponseUtils.getResponseData(ResultStateCode.SUCCESS, "操作成功", managerService.getById(id));
    }

    @RequestMapping("perms")
    public ResponseData getPerms(@RequestHeader("jwt") String jwt) {
        int id = JwtUtil.getId(jwt, audience.getBase64Secret());
        return ResponseUtils.getResponseData(ResultStateCode.SUCCESS, "操作成功", managerService.getPermsByManagerId(id));
    }
}
